package com.aepryus.loom;

import java.util.*;

public abstract class Task {
	private long taskID;
	private Date startTime;
	private String username;
	private List<Domain> delta =  new Vector<Domain>();
	private Stack<Domain> stack = new Stack<Domain>();

	public abstract String getName();
	public abstract Object process() throws PersistenceException,ValidationException,LockException;

	void setTaskID (long taskID) {this.taskID = taskID;}
	public long getTaskID () {return taskID;}
	void setStartTime (Date startTime) {this.startTime = startTime;}
	public Date getStartTime () {return startTime;}
	void setUsername (String username) {this.username = username;}
	public String getUsername () {return username;}

	void addDomain (Domain domain) {
		delta.add(domain);
		stack.add(domain);
	}

	void persist () throws LockException,ValidationException,PersistenceException {
		while (stack.size() > 0) {
			Domain domain = stack.pop();
			if (domain.getStatus() != Domain.DELETE) {
				domain.persist();
				domain.validate();
			}
		}

		try {
			for (Domain domain : delta) {
				DomainPort.clearQueryCache(domain.getDomain());
				Persist persist = Controller.controller.getPersist(domain.getDomain());
				persist.store(domain);
				if (domain.getStatus() == Domain.DELETE) DomainPort.unbind(domain);
				else domain.read();
			}
			SQL.commit();

		} catch (PersistenceException e) {
			try {
				SQL.rollback();
			} catch (PersistenceException e2) {/**/}
			throw e;
		} catch (RuntimeException e) {
			try {
				SQL.rollback();
			} catch (PersistenceException e2) {/**/}
			throw e;
		}
	}
	void unwind () {
		for (Domain domain : delta)
			DomainPort.unbind(domain);
	}
}

